﻿using System;
using System.Xml;
using System.Linq;
using System.Collections.Generic;

namespace Infrastructure.Serialization
{
    public static class SerializerExtensions
    {
        public static ClassType Deserialize<ClassType>(this ISerializer serializer, XmlNode node) where ClassType : class
        {
            var obj = serializer.Deserialize(node);
            if (typeof(ClassType).IsAssignableFrom(obj.GetType())) return (ClassType)obj;
            return null;
        }

        public static IEnumerable<ClassType> DeserializeNodesOfType<ClassType>(this ISerializer serializer, XmlNode parentNode) where ClassType : class
        {
            return parentNode.SelectNodes(typeof(ClassType).Name)
                .Cast<XmlNode>().Select(node => serializer.Deserialize<ClassType>(node)).Where(obj => obj != null);
        }

        public static void SerializeCollection<ItemType>(this ISerializer serializer, XmlNode parentNode, IEnumerable<ItemType> source)
        {
            source.ToList().ForEach(item => serializer.Serialize(item, parentNode));
        }
    }
}
